package com.eva.framework.common.banner;

import org.springframework.boot.ApplicationRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.core.env.Environment;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.InputStreamReader;

/**
 * 应用信息Runner，在应用启动后输出应用信息
 * 说明：在resources下存放application.txt文件，启动后将自动输出内容，内容可使用应用配置变量
 */
@Component
public class ApplicationBanner {

    private final Environment environment;

    public ApplicationBanner(Environment environment) {
        this.environment = environment;
    }

    @Bean
    public ApplicationRunner applicationBannerRunner() {
        return args -> {
            // 从资源文件中读取application.txt
            Resource resource = new ClassPathResource("application.txt");
            try (BufferedReader reader = new BufferedReader(new InputStreamReader(resource.getInputStream()))) {
                StringBuilder banner = new StringBuilder();
                String line;
                while ((line = reader.readLine()) != null) {
                    banner.append(line).append("\n");
                }

                // 解析占位符
                String resolvedBanner = environment.resolvePlaceholders(banner.toString());
                System.out.println(resolvedBanner);
            } catch (Exception ignored) {
            }
        };
    }
}
